package cn.com.zero.sample.user.service.impl;


import cn.com.zero.api.message.dubbo.IMessageService;
import cn.com.zero.base.constant.ZeroConstants;
import cn.com.zero.base.exception.ErrorCodeException;
import cn.com.zero.base.service.BaseService;
import cn.com.zero.sample.user.po.User;
import cn.com.zero.sample.user.service.UserService;
import cn.com.zero.sample.user.vo.UserInfo;
import cn.com.zero.web.util.HttpRequestUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhoupeng
 * @version 1.0.0
 * @Description
 * @createTime 2022-07-11
 */
@Validated
@Service
public class UserServiceImpl extends BaseService implements UserService {

    private final static String register_code_message_type = "code_register_user";
    private final static String login_code_message_type = "code_login_user";
    private final static String register_success_message_type = "register_success";
    private final static String login_success_message_type = "login_success";

    /**
     * 用户数据库
     */
    private Map<String, User> userDB = new HashMap<>();
    private IMessageService messageService;

    @Override
    public UserInfo register(String username, String password, String nick) {

        if (userDB.containsKey(username)) {
            logger.warn("{}用户已存在", username);
            throw new ErrorCodeException(-10007, new String[]{username});
        }
        // 保存到数据库
        User user = new User();
        user.setUsername(username);
        user.setNick(nick);
        user.setPassword(password);
        userDB.put(username, user);

        // 返回 vo 对象
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(user, userInfo);
        logger.info("{}用户注册成功", username);
        return userInfo;
    }

    @Override
    public UserInfo login(String username, String password) {

        User user = userDB.get(username);
        if (user == null || !StrUtil.equals(user.getPassword(), password)) {
            throw new ErrorCodeException(-10008);
        }
        // 返回 vo 对象
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(user, userInfo);
        logger.debug("{}用户登陆成功", username);
        return userInfo;
    }

    @Override
    public void sendRegisterCode(String phone) {
        messageService.sendVerificationCode(phone, register_code_message_type, HttpRequestUtil.getRequestIp());
    }

    @Override
    public String registerByPhone(String phone, String verificationCode) {
        // 验证 验证码
        Long checkResult = messageService.checkVerificationCode(phone, register_code_message_type, verificationCode);
        if (checkResult.compareTo(ZeroConstants.RETURN_CODE_SUCCESS) != 0) {
            throw new ErrorCodeException(checkResult);
        }
        // 验证 用户是否已经存在
        if (userDB.containsKey(phone)) {
            logger.warn("{}用户已存在", phone);
            throw new ErrorCodeException(-10007, new String[]{phone});
        }

        // 保存到数据库
        User user = new User();
        user.setUsername(phone);
        user.setNick(phone);
        userDB.put(phone, user);

        logger.info("{}用户注册成功", phone);
        String registerTime = DateUtil.formatDateTime(new Date());
        String message = "恭喜您，使用手机号码{}注册成功！注册时间为：{}。";
        // 发送注册成功短信
        messageService.sendMessage(phone, register_success_message_type, HttpRequestUtil.getRequestIp(), phone, registerTime);
        return StrUtil.format(message, phone, registerTime);
    }

    @Override
    public void sendLoginCode(String phone) {
        messageService.sendVerificationCode(phone, login_code_message_type, HttpRequestUtil.getRequestIp());
    }

    @Override
    public String loginByPhone(String phone, String verificationCode) {
        // 验证 验证码
        Long checkResult = messageService.checkVerificationCode(phone, login_code_message_type, verificationCode);
        if (checkResult.compareTo(ZeroConstants.RETURN_CODE_SUCCESS) != 0) {
            throw new ErrorCodeException(checkResult);
        }
        // 验证 用户存在
        User user = userDB.get(phone);
        if (null == user) {
            throw new ErrorCodeException(-10008);
        }

        logger.debug("{}用户登陆成功", phone);
        String loginTime = DateUtil.formatDateTime(new Date());
        String message = "恭喜您，使用手机号码{}登录成功！登录时间为：{}。";
        // 发送注册成功短信
        messageService.sendMessage(phone, login_success_message_type, HttpRequestUtil.getRequestIp(), phone, loginTime);
        return StrUtil.format(message, phone, loginTime);
    }

    @Autowired(required = false)
    @DubboReference
    public void setMessageService(IMessageService messageService) {
        this.messageService = messageService;
    }
}
